/*
 * AIEngine a new generation network intrusion detection system.
 *
 * Copyright (C) 2013-2023  Luis Campo Giralte
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
 * Boston, MA  02110-1301, USA.
 *
 * Written by Luis Campo Giralte <luis.camp0.2009@gmail.com> 
 *
 */
#include "TCPGenericProtocol.h"
#include <iomanip> // setw

namespace aiengine {

bool TCPGenericProtocol::check(const Packet &packet){

	setHeader(packet.getPayload());
	++total_valid_packets_;
	return true;
}

void TCPGenericProtocol::processFlow(Flow *flow) {

	CPUCycle cycles(&total_cpu_cycles_);
	++total_packets_;
	total_bytes_ += flow->packet->getLength();

	++flow->total_packets_l7;

	if (flow->regex_mng) {
		const uint8_t *payload = flow->packet->getPayload();
		boost::string_ref data(reinterpret_cast<const char*>(payload), flow->packet->getLength());

		eval_.processFlowPayloadLayer7(flow, data);
	}
}

void TCPGenericProtocol::statistics(std::basic_ostream<char> &out, int level, int32_t limit) const {

	showStatisticsHeader(out, level);

	if ((level > 5)and(flow_forwarder_.lock()))
		flow_forwarder_.lock()->statistics(out);

	if ((level > 3)and(rm_))
		rm_->statistics(out);
}

void TCPGenericProtocol::statistics(Json &out, int level) const {          

	showStatisticsHeader(out, level);
}

void TCPGenericProtocol::setRegexManager(const SharedPointer<RegexManager> &rm) {

	if (rm_)
		rm_->setPluggedToName("");

	if (rm) {
		rm_ = rm;
		rm_->setPluggedToName(name());
	} else {
		rm_.reset();
	}
}

CounterMap TCPGenericProtocol::getCounters() const {
	CounterMap cm;

        cm.addKeyValue("packets", total_packets_);
        cm.addKeyValue("bytes", total_bytes_);

        return cm;
}

void TCPGenericProtocol::resetCounters() {

	reset();
}

} // namespace aiengine
